package top.fengyulou.xiaofeng.common.controller;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import top.fengyulou.xiaofeng.common.Jr;
import top.fengyulou.xiaofeng.common.UuidUtil;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传文件功能
 */
@Controller
@Slf4j
public class UploadFileController {
    public static final String UPLOAD_TRUE = "上传成功";
    public static final String UPLOAD_FALSE = "上传失败";
    public static final String UPLOAD_ERROR = "文件格式不正确！只支持上传：";
    @Value("${file.path}")
    private String filePath;

    /**
     * 上传图片
     */
    @RequestMapping("/upload/img")
    @ResponseBody
    public Jr uploadImg(@RequestParam MultipartFile file, @RequestParam String dir) {
        String[] suffixs = {"jpg", "jpeg", "png"};
        return uploadFile(file, dir, suffixs);
    }

    /**
     * 上传音频
     */
    @RequestMapping("/upload/mp3")
    @ResponseBody
    public Jr uploadMp3(@RequestParam MultipartFile file, @RequestParam String dir) {
        String[] suffixs = {"mp3"};
        return uploadFile(file, dir, suffixs);
    }

    /**
     * 上传视频
     */
    @RequestMapping("/upload/mp4")
    @ResponseBody
    public Jr uploadMp4(@RequestParam MultipartFile file, @RequestParam String dir) {
        String[] suffixs = {"mp4"};
        return uploadFile(file, dir, suffixs);
    }

    /**
     * 保存文件
     *
     * @param file
     * @param dir
     * @param suffixs
     * @return
     */
    public Jr uploadFile(MultipartFile file, String dir, String[] suffixs) {
        try {
            //验证文件后缀
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            boolean checkSuffix = false;
            for (String s : suffixs) {
                if (s.equals(suffix)) {
                    checkSuffix = true;
                    break;
                }
            }
            if (!checkSuffix) {
                return Jr.nom(UPLOAD_ERROR + StringUtils.join(suffixs, ","));
            }

            //创建文件目录
            String baseDir = "/upload/" + dir + "/" + DateUtil.format(new Date(), "yyyyMMdd");
            File fullDir = new File(filePath + baseDir);
            if (!fullDir.exists()) {
                fullDir.mkdirs();
            }

            //保存文件
            String key = UuidUtil.getShortUuid();//新文件名称
            String path = baseDir + "/" + key + "." + suffix;//文件保存相对路径
            String fullPath = filePath + path;//文件保存绝对路径
            File dest = new File(fullPath);
            file.transferTo(dest);//保存文件

            //返回结果
            Map<String, Object> map = new HashMap<>();
//            map.put("url", domainName + path);//文件访问路径
            map.put("url", "/file"+path);//文件访问路径
            map.put("uri", path);//文件相对路径
            return Jr.yes(UPLOAD_TRUE, map);
        } catch (Exception e) {
            log.error("UploadFileController.uploadFile", e);
            return Jr.yesm(UPLOAD_FALSE);
        }
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public void deleteFile(String path) {
        if (ObjectUtils.isNotEmpty(path)) {
            File file = new File(filePath + path);
            file.delete();
        }
    }
}
